package com.flow.framework.base.service.alarm.impl;

import com.flow.framework.base.properties.FrameworkBaseConfigProperties;
import com.flow.framework.base.service.alarm.IAlarmService;
import com.flow.framework.common.json.JsonObject;
import com.flow.framework.common.util.verify.VerifyUtil;
import com.flow.framework.facade.alarm.module.service.IAlarmFrameworkModuleService;
import com.flow.framework.facade.alarm.pojo.dto.AlarmClearModuleDto;
import com.flow.framework.facade.alarm.pojo.dto.AlarmReportModuleDto;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * 告警服务
 *
 * @author luoguopiao
 * @version 0.0.1
 * @date 2022/12/11
 */
@Slf4j
@RequiredArgsConstructor
public class AlarmServiceImpl implements IAlarmService {

    private final IAlarmFrameworkModuleService alarmFrameworkModuleService;

    private final FrameworkBaseConfigProperties frameworkBaseConfigProperties;

    private volatile boolean health = true;

    @Override
    @SuppressWarnings("deprecation")
    public boolean getAndResetHealth(){
        if (health){
            return true;
        } else {
            boolean result = health;
            health = true;
            return result;
        }

    }

    /**
     * @inheritDoc
     */
    @Override
    public void reportAlarm(AlarmReportModuleDto alarmReportModuleDto) {
        if (!VerifyUtil.isTrue(frameworkBaseConfigProperties.getEnableAlarmService())) {
            if (health) {
                health = false;
            }
            log.error("report_alarm : {}", JsonObject.toString(alarmReportModuleDto));
            return;
        }
        try {
            alarmFrameworkModuleService.reportAlarm(alarmReportModuleDto);
        } catch (Exception e) {
            if (health) {
                health = false;
            }
            log.error("report_alarm : {}, but occurred error.", JsonObject.toString(alarmReportModuleDto), e);
        }
    }

    /**
     * @inheritDoc
     */
    @Override
    public void clearAlarm(AlarmClearModuleDto alarmClearModuleDto) {
        if (!VerifyUtil.isTrue(frameworkBaseConfigProperties.getEnableAlarmService())) {
            if (health) {
                health = false;
            }
            log.error("clear_alarm : {}", JsonObject.toString(alarmClearModuleDto));
            return;
        }
        try {
            alarmFrameworkModuleService.clearAlarm(alarmClearModuleDto);
        } catch (Exception e) {
            if (health) {
                health = false;
            }
            log.error("clear_alarm : {}, but occurred error.", JsonObject.toString(alarmClearModuleDto), e);
        }
    }
}
